package cn.cdeden.knowledge.service.impl;

import cn.cdeden.common.core.utils.MapstructUtils;
import cn.cdeden.knowledge.domain.SysCalendar;
import cn.cdeden.knowledge.domain.SysCalendarSharing;
import cn.cdeden.knowledge.domain.SysSchedule;
import cn.cdeden.knowledge.domain.dto.SysCalendarDto;
import cn.cdeden.knowledge.domain.dto.SysScheduleDto;
import cn.cdeden.knowledge.mapper.SysScheduleMapper;
import cn.cdeden.knowledge.service.SysCalendarService;
import cn.cdeden.knowledge.service.SysCalendarSharingService;
import cn.cdeden.knowledge.service.SysScheduleService;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class SysScheduleServiceImpl extends ServiceImpl<SysScheduleMapper, SysSchedule> implements SysScheduleService {

    @Autowired
    private SysCalendarSharingService sysCalendarSharingService;

    @Autowired
    private SysCalendarService sysCalendarService;

//    @Autowired
//    private ProjectTaskService projectTaskService;

    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
    private static final SimpleDateFormat DATE_TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public List<SysScheduleDto> getAllAndPermission(List<Long> scheduleIds, Long userId) {
        List<SysScheduleDto> allAndPermission = getBaseMapper().getAllAndPermission(scheduleIds, userId);
        allAndPermission.forEach(v -> {
            v.setSysScheduleState("false");
            if (v.getDetailsId() != null && v.getDetailsId().equals(1l)) {
                v.setSysScheduleState("true");
            }
        });
        return allAndPermission;
    }

    @Override
    public List<Long> getAllAndDetails(Long scheduleId, Long userId) {
        return getBaseMapper().getAllAndDetails(scheduleId, userId);
    }

    @Override
    public Boolean deleteBatchPersonnel(Long scheduleId, List<Long> userIds) {
        return getBaseMapper().deleteBatchPersonnel(scheduleId, userIds);
    }

    @Override
    public Boolean deleteBatchPermissions(Long scheduleId, List<Long> userIds) {
        return getBaseMapper().deleteBatchPermissions(scheduleId, userIds);
    }

    @Override
    public List<SysCalendarDto> attentionShow(List<Long> userIds, Date startDate, Date endDate) {
        LocalDateTime startDateTime = startDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        LocalDateTime endDateTime = endDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String startTime = startDateTime.format(dateTimeFormatter);
        String endTime = endDateTime.format(dateTimeFormatter);
        //查询出日程所有的分享数据
        List<SysCalendarSharing> sysCalendarSharingList = sysCalendarSharingService.list();
        List<Long> calendarIds = new ArrayList<Long>();
        sysCalendarSharingList.forEach(sysCalendarSharing -> {
            List<Long> containIds = JSONUtil.toList(sysCalendarSharing.getCalendarSharingId(), Long.class);
            if (userIds.stream().anyMatch(containIds::contains)) {
                calendarIds.add(sysCalendarSharing.getCalendarId());
            }
        });
        List<SysCalendar> sysCalendarList = new ArrayList<>();
        if (!calendarIds.isEmpty()) {
            sysCalendarList = sysCalendarService.list(new QueryWrapper<SysCalendar>()
                    .in("id", calendarIds)
                    .between("start_date", startTime, endTime)
                    .between("end_date", startTime, endTime));
        }
        List<SysCalendarDto> sysCalendarDtos = MapstructUtils.convert(sysCalendarList, SysCalendarDto.class);
        //加入工时任务的数据
        List<SysCalendarDto> myTaskList = new ArrayList<>();
//        userIds.forEach(v -> {
//            List<Map<String, Object>> myWorkList = projectTaskService.queryMyTaskCalendar(startDate, endDate, Long.toString(v));
//            myWorkList.forEach(map -> {
//                try {
//                    Date myTaskStartDate = parseDate((String) map.get("startDate"), true);
//                    Date myTaskSEndDate = parseDate((String) map.get("endDate"), false);
//                    SysCalendarDto sysCalendarDto = SysCalendarDto.builder()
//                            .myTaskId((String) map.get("id"))
//                            .label((String) map.get("label"))
//                            .content((String) map.get("content"))
//                            .startDate(myTaskStartDate)
//                            .endDate(myTaskSEndDate)
//                            .build();
//                    myTaskList.add(sysCalendarDto);
//                } catch (ParseException e) {
//                    e.printStackTrace();
//                }
//            });
//        });
        sysCalendarDtos.addAll(myTaskList);
        return sysCalendarDtos;
    }
    // 日期解析方法，处理转换异常
    private Date parseDate(String dateStr, boolean isStartDate) throws ParseException {
        if (dateStr == null || dateStr.isEmpty()) {
            return null;
        }
        String timeStr = isStartDate ? "00:00:00" : "23:59:59";
        String formattedDateStr = dateStr + " " + timeStr;
        return DATE_TIME_FORMAT.parse(formattedDateStr);
    }
}
